/**
 * Created by tianling on 2016/12/25.
 */

module.exports = class {
    constructor() {

        this.key = "iframe:systemModule";
    }

    static init() {
        return new this();
    }

    /**
     * 获取系统模块列表
     * @param isReFlash
     * @param CB
     */
    async getSystemModule(isReFlash) {
        let ret = [];
        if (isReFlash) {
            ret = await global.DataBase.iframe_system_module.Access.findAll({
                order: [
                    ['Sort', 'ASC']
                ],
                raw: true
            });
        } else {
            if (!global.Config.isShareMemory) {
                ret = JSON.parse(JSON.stringify(global.systemModule));
            } else {
                let redisClient = global.Redis.getClient();
                let retStr = await redisClient.get(this.key);
                if (retStr) {
                    ret = JSON.parse(retStr);
                }

            }

            if (!ret) {
                ret = await global.DataBase.iframe_system_module.Access.findAll({
                    order: [
                        ['Sort', 'ASC']
                    ],
                    raw: true
                });
            }
        }
        return ret;

    }

    async Sync() {
        let systemModule = await this.getSystemModule(true);
        if (!global.Config.isShareMemory) {
            global.systemModule = systemModule;
        } else {
            let redisClient = global.Redis.getClient();
            await redisClient.set(this.key, JSON.stringify(systemModule));
        }

        log.info("加载系统模块成功");
        return true;
    }

    /**根据ID查找Module**/
    GetModuleByID(ModuleItems, ModuleID) {
        let Module = {};
        for (let i = 0; i < ModuleItems.length; i++) {
            let item = ModuleItems[i];
            if (item.ModuleID == ModuleID) {
                return item;
            }
        }
        return null;
    }


    /**
     * 根据用户角色获取权限
     */
    async getUserModule(_UserRules, _partnersId) {
        let SystemModules = await this.getSystemModule(false);
        let UserRules = _UserRules.split(',');
        let _modules = [];
        for (let ii = 0; ii < UserRules.length; ii++) {
            let __modules = [];
            let item = UserRules[ii];
            if (item == "-9999") {
                if (_partnersId > 0) { //企业超管 
                    let partnersModel = await global.DataBase.v_iframe_partners.Access.find({
                        attributes: ['RuleAble'],
                        where: {
                            OS_ID: _partnersId
                        },
                        raw: true
                    });
                    if (partnersModel) {
                        let RuleAble = JSON.parse(partnersModel.RuleAble);
                        for (let a = 0; a < RuleAble.length; a++) {
                            for (let b = 0; b < SystemModules.length; b++) {
                                if (RuleAble[a].M && RuleAble[a].M == SystemModules[b].ModuleID) {
                                    SystemModules[b].Able = RuleAble[a].A;
                                    SystemModules[b].DataOptions = '';
                                    __modules.push(SystemModules[b]);
                                }
                            }
                        }
                    }
                } else { //平台超管
                    for (let i in SystemModules) {
                        SystemModules[i].Able = "";
                        SystemModules[i].DataOptions = "";
                    }
                    __modules = SystemModules;
                }
            } else {
                let rule = await global.DataBase.iframe_rule.Access.findById(Number(item));
                let _RuleAbleList = JSON.parse(rule.RuleAble);
                if (_RuleAbleList && _RuleAbleList instanceof Array && _RuleAbleList.length > 0) {
                    for (let c = 0; c < _RuleAbleList.length; c++) {
                        for (let i = 0; i < SystemModules.length; i++) {
                            if (_RuleAbleList[c].M == SystemModules[i].ModuleID) {
                                SystemModules[i].Able = _RuleAbleList[c].A;
                                SystemModules[i].DataOptions = _RuleAbleList[c].D;
                                __modules.push(SystemModules[i]);
                            }
                        }
                    }
                }


            }
            _modules.push(__modules);
        }
        let ModuleList = [];
        if (_modules && _modules.length > 0) {
            for (let i = 0; i < _modules.length; i++) {
                if (_modules[i]) {
                    for (let j = 0; j < _modules[i].length; j++) {
                        let isHas = false;
                        for (let m in ModuleList) {
                            if (ModuleList[m].ModuleID == _modules[i][j].ModuleID) {
                                isHas = true;
                                break;
                            }
                        }
                        if (!isHas) {
                            ModuleList.push(_modules[i][j]);
                        }
                    }
                }

            }
        }

        ModuleList.sort(function (a, b) {
            return a.Sort - b.Sort;
        });

        return ModuleList;

    }

    /**根据URL查找Module**/
    GetModuleByUrl(ModuleItems, Url) {
        if (Url) {
            for (let i = 0; i < ModuleItems.length; i++) {
                let item = ModuleItems[i];
                if (item.URL && item.URL.toLowerCase() == Url.toLowerCase()) {
                    return item;
                }
            }
        }
        return null;
    }


    /**
     * 根据用户角色获取权限
     */
    async getRuleAble(_UserRules, _partnersId) {
        let ret = await this.getUserModule(_UserRules, _partnersId);
        let _RuleAbleList = [];
        for (let i = 0; i < ret.length; i++) {
            let RA = {
                M: ret[i].ModuleID,
                A: ret[i].Able,
                D: ret[i].DataOptions
            };
            _RuleAbleList.push(RA);

        }
        return _RuleAbleList;
    }

    /**根据指向类型（UrlGoModuleID）从最上层向下查找，找到有自定义Url的最低层的Module**/
    FindTargetModule(ModuleItems, ModuleID) {
        let Module = this.GetModuleByID(ModuleItems, ModuleID);
        if (!Module) return null;
        switch (Module.UrlGoModuleID) {
            case -1:
                /**自适应（找到可用的下级，不一定是直接下级）**/
                for (let i in ModuleItems) {
                    if (ModuleItems[i].ParentID == ModuleID && ModuleItems[i].IsShowInMenu > 0) {
                        return this.FindTargetModule(ModuleItems, ModuleItems[i].ModuleID);
                        break;
                    }
                }
                return null;
                break;
            case 0:
                /**自定义**/
                return Module;
                break;
            default:
                /**具体指向到下级的模块**/
                return this.FindTargetModule(ModuleItems, Module.UrlGoModuleID);
                break;
        }
    }

    /**获取所有的父级ID**/
    GetParentIds(ModuleItems, moduleId) {
        let Parents = [];
        let Module = this.GetModuleByID(ModuleItems, moduleId);
        if (Module) {
            Parents.push(Module.ParentID + "");
            Parents = Parents.concat(this.GetParentIds(Module.ParentID));
        }
        return Parents;
    }
}